package cmd

import (
	"fmt"
	"im-tools/internal/config"
	"im-tools/internal/model"
	"net/http"

	_ "im-tools/pkg"

	"github.com/duke-git/lancet/netutil"
	"github.com/goccy/go-json"
	"github.com/gookit/color"
	"github.com/spf13/cobra"
)

var (
	Token            string // HTTP token
	IMToken          string // IM 认证Token
	LoginedUserId    string // 当前登录用户ID
	LoginedDeviecode string // 当前登录的设备ID
)

var loginCmd = &cobra.Command{
	Use:   "login",
	Short: "登录",
	Long:  `登录IM Web系统`,
	Run: func(cmd *cobra.Command, args []string) {

		var loginAccount string
		// loginAccount, _ := cmd.Flags().GetString("account")

		for {
			color.Info.Println("请输入账号:")
			if _, err := fmt.Scanln(&loginAccount); err != nil {
				continue
			}
			if loginAccount != "" {
				break
			}
		}
		request := &netutil.HttpRequest{
			RawURL: config.API + "/api/zkim/sys/userLogin",
			Method: "POST",
		}

		loginReq := &model.LoginReq{
			DeviceType:    "ANDROID",
			LoginAccount:  loginAccount,
			LoginPassword: "",
			LoginType:     2,
		}

		postData, err := json.Marshal(loginReq)
		if err != nil {
			fmt.Println(err)
		}
		request.Body = postData

		headers := http.Header{}
		headers.Add("Content-Type", "application/json")
		request.Headers = headers

		httpClient := netutil.NewHttpClient()
		resp, err := httpClient.SendRequest(request)
		if err != nil || resp.StatusCode != 200 {
			fmt.Println(resp.StatusCode)
			return
		}

		var loginResp model.LoginResp
		r := &model.R{
			Data: loginResp,
		}
		err = httpClient.DecodeResponse(resp, r)
		if err != nil {
			fmt.Println(err)
		}

		if resp, ok := r.Data.(map[string]interface{}); ok {
			LoginedDeviecode = resp["deviceCode"].(string)
			LoginedUserId = resp["fakeId"].(string)
			Token = resp["token"].(string)
			IMToken = resp["imToken"].(string)
		}

		fmt.Println(loginAccount + " 登录成功!")
		// ui.RenderTable()
	},
}

func init() {
	// loginCmd.Flags().StringP("account", "a", "", "输入登录账号")
	rootCmd.AddCommand(loginCmd)
}
